home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8067 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  56 lines

  1. Path: news.telalink.net!news
  2. From: daver@nashville.net (David Rawle)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Global Variables
  5. Date: 14 Feb 1996 06:00:53 GMT
  6. Organization: Telalink Corporation, Nashville, TN, USA
  7. Message-ID: <4frtql$73t@adam.telalink.net>
  8. References: <4fefbm$dhf@tofu.alt.net>
  9. NNTP-Posting-Host: nash-pm1-a25.telalink.net
  10. Mime-Version: 1.0
  11. X-Newsreader: WinVN 0.99.3
  12.  
  13. In article <4fefbm$dhf@tofu.alt.net>, ljbuller@mail.btigate.com says...
  14. >
  15. >Help!!! I'm using visualc++ 4.0.  What I want to do is recall information 
  16. >from an ini file... I already know how to do that.  What I can't seem to 
  17. >figure out is how to reference global variables in other classes.  For 
  18. >instance I can declare a variable outside of functions and class and That 
  19. >is supposed to make it global.  If I delcare x in 1.h and define it in 
  20. >1.cpp then try to refer to x in 2.cpp I get an undeclared variable error. 
  21. >If I make sure the declaration also exists in the 2.h, then I get a 
  22. linker 
  23. >error.  I know this has got to be a real simple answer, but I'll be 
  24. darned 
  25. >if I can find the answer.  Any body got help for this soul lost in c++ 
  26. >hell?   Larry Buller
  27. >
  28.  
  29. You don't state what the linker error is, but I would guess it is
  30. something like x in module "..." is also defined in module "...".
  31. You should never define global variables in .h files.  You might
  32. declare them such as:
  33.  
  34. 1.h:
  35. ...
  36. extern MyType x;
  37. ...
  38.  
  39. and then in some file such as globals.cpp
  40.  
  41. ...
  42. MyType x;
  43. ...
  44.  
  45. The extern allows the code to compile and later the linker resolves
  46. the extern reference to the variable defined in the .cpp. Without
  47. the extern you are trying to create two separate variables with the
  48. same name.
  49.  
  50. You might want to check out the K&R book on C programming.
  51.  
  52. If I have misdiagnosed your problem, sorry.
  53.  
  54. Daver
  55.  
  56.